/*******************************************************************************
 * Software Name : Android Simple Downloader
 *
 * Copyright © 2012 Rinvay Tang
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package com.rinvay.network.http.conn.impl;

import java.io.IOException;
import java.net.MalformedURLException;

import com.rinvay.network.http.HttpRequest;
import com.rinvay.network.http.conn.HttpConnection;
import com.rinvay.network.http.exception.ErrorMessage;
import com.rinvay.network.http.exception.NetWorkInvalidException;

/**
 * most used default http connection
 * @author rinvay
 * @date 2012-3-10
 */
public class DefaultHttpConnection extends HttpConnection
{
    private static final String TAG = "DefaultHttpConnection";

    protected DefaultHttpConnection(HttpRequest r) {
        this(r, null);
    }

    protected DefaultHttpConnection(HttpRequest request,
            DefaultHttpConnectionListener listener) {
        this.request = request;
        this.listener = listener;
    }

    @Override
    public void run() {
        httpConnectionState = CONNECTION_STATE_CONNECTING;
        if (listener != null) {
            listener.onConnecting();
        }

        boolean hasException = false;
        try {
            connect();
        } catch (NetWorkInvalidException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            hasException = true;
            if (listener != null) {
                listener.onError(ErrorMessage.ERROR_CODE_NETWORK_INVALID, null);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            hasException = true;
            if (listener != null) {
                listener.onError(ErrorMessage.ERROR_CODE_MALFORMED_URL, null);
            }
        } catch (IOException e) {
            hasException = true;
            e.printStackTrace();
            if (listener != null) {
                listener.onError(ErrorMessage.ERROR_CODE_OPEN_CONNECTION, null);
            }
        } finally {
            if(hasException) {
                close();
                return;
            }
        }

        httpConnectionState = CONNECTION_STATE_CONNECTED;
        if (listener != null) {
            listener.onConnected();
        }
        try {

            if (request.getData() != null && request.getData().length > 0) {
                sendData(request.getData());
            }

            int responseCode = conn.getResponseCode();
            if (responseCode / 100 == 2) {
                byte[] resp = getResponseData();

                if (listener != null) {
                    ((DefaultHttpConnectionListener) listener).onResponse(resp);
                }
            } else {
                if (listener != null) {
                    listener.onError(responseCode, null);
                }
            }

            httpConnectionState = CONNECTION_STATE_FINISH;
       
        } catch (IOException e) {
            e.printStackTrace();
            if (listener != null) {
                listener.onError(0, null);
            }
        } finally {
            close();
        }
    }

    /**
     * get response byte data
     * @return
     * @throws IOException
     */
    private byte[] getResponseData() throws IOException {
        byte[] resData = null;
        resData = readStream(getInputStream());
        return resData;
    }

}
